//
//  XDMyInviteViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/3/14.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDMyInviteViewController.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDMyInviteModel.h"
#import "MJExtension.h"
#import "XDBMyUserInfoheaderView.h"
#import "XDMyInviteCell.h"
#import "SVPullToRefresh.h"
#import "XDLoadingView.h"
@interface XDMyInviteViewController ()<UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>


@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *resultArr;

@property (nonatomic, strong) NSMutableArray *mutArr;

@property (nonatomic, strong) NSArray *pickerArr;

@property (nonatomic, weak) UILabel *noData;

@property (nonatomic,weak) UIButton *rightBarBtn;

//点击title弹出框的背景view
@property (nonatomic, weak) UIView *titleCoverView;

@property (nonatomic, weak) UIView *selectView;

@property (nonatomic, weak) UIView *dateView;
@property (nonatomic, weak) UIPickerView *pickerView;
@property (nonatomic, copy) NSString *dateStr;
@end

@implementation XDMyInviteViewController
- (NSMutableArray *)resultArr {
    if (_resultArr == nil) {
        _resultArr = [NSMutableArray array];
    }
    return _resultArr;
}

- (NSArray *)pickerArr {
    
    if (_pickerArr == nil) {
        _pickerArr = @[
                       @[@"2010年",@"2011年",@"2012年",@"2013年",@"2014年",@"2015年",@"2016年",@"2017年",@"2018年",@"2019年",@"2020年"],
                       @[@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月",@"8月",@"9月",@"10月",@"11月",@"12月"]];
    }
    return _pickerArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"我的邀请";
     self.view.backgroundColor = kColorRGB(234, 234, 234);
    [self setUI];
    [self loadData];
    
    [self.tableView addPullToRefreshWithActionHandler:^{
        [self loadData];
    }];
    
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [self loadData];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    XDLoadingView *loading = [[XDLoadingView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 60)];
    
//    loading.backgroundColor = [UIColor redColor];
    [self.tableView.pullToRefreshView setCustomView:loading forState:SVPullToRefreshStateAll];
    
    
    
     XDLoadingView *loading1 = [[XDLoadingView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 60)];
    [self.tableView.infiniteScrollingView setCustomView:loading1 forState:SVInfiniteScrollingStateAll];
}


- (void)setUI {
    
    
    UIView *headerBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 44)];
    headerBackView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerBackView];
    
    UILabel *sumCountLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW * 0.5, 44)];
    sumCountLb.text = @"好友总数: 0人";
    sumCountLb.textColor = kColorRGB(102, 102, 102);
    sumCountLb.textAlignment = NSTextAlignmentCenter;
    sumCountLb.font = kBaseFont_(13);
    [headerBackView addSubview:sumCountLb];
    
    UILabel *yesterdayCountLb = [[UILabel alloc] initWithFrame:CGRectMake(kScreenW * 0.5, 0, kScreenW * 0.5, 44)];
    yesterdayCountLb.text = @"昨日新增: 0人";
    yesterdayCountLb.textColor = kColorRGB(102, 102, 102);
    yesterdayCountLb.textAlignment = NSTextAlignmentCenter;
    yesterdayCountLb.font = kBaseFont_(13);
    [headerBackView addSubview:yesterdayCountLb];
    
    UIView *coverVView = [[UIView alloc] initWithFrame:CGRectMake(kScreenW * 0.5, 8, 1, 28)];
    coverVView.backgroundColor = kColorRGBA(0, 0, 0, 0.1);
    [headerBackView addSubview:coverVView];
    
    UIView *coverHView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, kScreenW, 1)];
    coverHView.backgroundColor = kColorRGBA(0, 0, 0, 0.1);
    [headerBackView addSubview:coverHView];
    
    
    UIView *catalogueView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerBackView.frame) + 10, kScreenW, 44)];
    catalogueView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:catalogueView];
    
    UILabel *numberLb = [[UILabel alloc] init];
    numberLb.text = @"序号";
    numberLb.textColor = kColorRGB(102, 102, 102);
    numberLb.font = kBaseFont_(12);
    [numberLb sizeToFit];
    numberLb.frame = CGRectMake(15, 0, numberLb.frame.size.width, 44);
    [catalogueView addSubview:numberLb];
    
   
    UILabel *friendLb = [[UILabel alloc] init];
    friendLb.text = @"好友名";
    friendLb.textColor = kColorRGB(102, 102, 102);
    friendLb.font = kBaseFont_(12);
    [friendLb sizeToFit];
    friendLb.frame = CGRectMake(CGRectGetMaxX(numberLb.frame) + 40 * kscaleW, 0, friendLb.frame.size.width, 44);
    [catalogueView addSubview:friendLb];
    
    UILabel *timeLb = [[UILabel alloc] init];
    timeLb.text = @"注册时间";
    timeLb.textColor = kColorRGB(102, 102, 102);
    timeLb.font = kBaseFont_(12);
    [timeLb sizeToFit];
    timeLb.frame = CGRectMake(kScreenW - timeLb.frame.size.width - 15, 0, timeLb.frame.size.width, 44);
    [catalogueView addSubview:timeLb];
    
    
    UILabel *mobleLb = [[UILabel alloc] init];
    mobleLb.text = @"手机号码";
    mobleLb.textColor = kColorRGB(102, 102, 102);
    mobleLb.font = kBaseFont_(12);
    [mobleLb sizeToFit];
    mobleLb.frame = CGRectMake(kScreenW - mobleLb.frame.size.width - timeLb.frame.size.width - 100 * kscale, 0, mobleLb.frame.size.width, 44);
    [catalogueView addSubview:mobleLb];
    NSLog(@"%@ ---- %@", NSStringFromCGPoint(friendLb.frame.origin), NSStringFromCGPoint(mobleLb.frame.origin));
    UIView *cover = [[UIView alloc] initWithFrame:CGRectMake(15, 43, kScreenW - 30, 1)];
    cover.backgroundColor = kColorRGBA(0, 0, 0, 0.1);
    [catalogueView addSubview:cover];
    
    UIView *coverTop = [[UIView alloc] initWithFrame:CGRectMake(0, -1, kScreenW, 1)];
    coverTop.backgroundColor = kColorRGBA(0, 0, 0, 0.1);
    [catalogueView addSubview:coverTop];
    
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(catalogueView.frame), kScreenW, kScreenH - CGRectGetMaxY(catalogueView.frame) - 64)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:tableView];
    self.tableView = tableView;
//    tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    tableView.tableFooterView = view;

    UIButton *rightBarBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    [rightBarBtn setBackgroundImage:[UIImage imageNamed:@"date"] forState:UIControlStateNormal];
    [rightBarBtn addTarget:self action:@selector(rightBarButtonItemClick:) forControlEvents:UIControlEventTouchUpInside];
    self.rightBarBtn = rightBarBtn;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarBtn];
    
}
- (void)loadData {
    
    self.dateStr = self.dateStr ? self.dateStr : @"";
    NSDictionary * param = @{@"method":@"getMyUserInfo",@"page":@"0",@"time":self.dateStr};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        [self.tableView.pullToRefreshView stopAnimating];
        [self.resultArr removeAllObjects];
        
        [self.mutArr removeAllObjects];
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            
            NSArray *arr = responseObject[@"result"][@"userList"];
            NSMutableArray *mutArr = [NSMutableArray arrayWithArray:arr];
            if (mutArr.count > 1) {
                for (int i =0; i<[mutArr count]-1; i++) {
                    for (int j =0; j<[mutArr count]-1-i; j++) {
                        
                        if(([mutArr[j][@"ctime"] compare:mutArr[j+1][@"ctime"]]) == NSOrderedAscending){
                            
                            //交换
                            
                            [mutArr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
                        }
                        
                    }
                    
                }
            }
            
            [self resultArray:mutArr];
            if (self.mutArr.count > 0) {
                [self.resultArr addObject:self.mutArr];
            }
            
            self.resultArr = [XDMyInviteModel mj_objectArrayWithKeyValuesArray:self.resultArr];
            
       
//                                              @"style": @"状态"
//                                              };
//            
            if (self.resultArr.count == 0) {
                UILabel *noData = [[UILabel alloc] initWithFrame:self.tableView.frame];
                noData.text = @"暂无数据";
                noData.textColor = kColorRGB(187,147,115);
                noData.font = kBaseFont_(16);
                noData.textAlignment = NSTextAlignmentCenter;
                self.noData = noData;
                [self.view addSubview:noData];
            } else {
                [self.noData removeFromSuperview];
            }
//
//            
//            
            [self.tableView reloadData];
            
        } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
            
            
        } else {
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
         [self.tableView.pullToRefreshView stopAnimating];
    }];
    
}
- (void)resultArray:(NSMutableArray *)arr
{
    if (arr.count > 0) {
        __block NSString *firstCtime = arr[0][@"ctime"];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [fmt dateFromString:firstCtime];
        //
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM";
        firstCtime = [dateFormatter stringFromDate:date];
        
        NSMutableArray *mutArr = [NSMutableArray array];
        self.mutArr = mutArr;
        [arr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *ctimeStr = [dateFormatter stringFromDate:[fmt dateFromString:dic[@"ctime"]]];
            if ([ctimeStr isEqualToString:firstCtime]) {
                [mutArr addObject:dic];
                
            } else{
                [self.resultArr addObject:mutArr];
                for (NSInteger i = 0; i < idx; i ++) {
                    [arr removeObjectAtIndex:0];
                }
                [self resultArray:arr];
            }
            
        }];
        
        for (NSInteger i = 0; i < arr.count; i ++) {
            [arr removeObjectAtIndex:0];
        }
    }
}



#pragma mark -- table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.resultArr[section];
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.resultArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *myID = @"XDMyInviteCell";
    XDMyInviteCell *cell = [tableView dequeueReusableCellWithIdentifier:myID];
    if (cell == nil) {
        cell = [[XDMyInviteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    XDMyInviteModel *model = self.resultArr[indexPath.section][indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *strId = @"XDBMyUserInfoheaderView";
    XDBMyUserInfoheaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:strId];
    if (view == nil) {
        view = [[XDBMyUserInfoheaderView alloc] initWithReuseIdentifier:strId];
    }
    XDMyInviteModel *model = self.resultArr[section][0];
    view.headerStr = model.ctime;
    return view;
}


- (void)rightBarButtonItemClick:(UIButton *)rightBarBtn {
    
    rightBarBtn.selected = !rightBarBtn.selected;
    if (rightBarBtn.selected) {
        self.titleCoverView.frame = kScreenB;
        [UIView animateWithDuration:0.5 animations:^{
            self.dateView.frame = CGRectMake(0, self.view.frame.size.height - 240, kScreenW, 240);
        } completion:^(BOOL finished) {
            
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            self.titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0);
            self.dateView.frame = CGRectMake(0, kScreenH, kScreenW, 240);
            
        } completion:^(BOOL finished) {
            [self.titleCoverView removeFromSuperview];
            [self.dateView removeFromSuperview];
        }];
        
        
    }
    
}
- (UIView *)titleCoverView {
    if (_titleCoverView == nil) {
        UIView *titleCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        _titleCoverView = titleCoverView;
        [self.view addSubview:titleCoverView];
        
    }
    
    return _titleCoverView;
}

- (UIView *)dateView {
    
    if (_dateView == nil) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH, kScreenW, 240)];
        
        view.backgroundColor = [UIColor whiteColor];
        
        UIView *toolView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 40)];
        toolView.backgroundColor = kColorRGB(249, 249, 249);
        [view addSubview:toolView];
        
        UIImage *img = [UIImage imageNamed:@"Plus"];
        UIButton *cancalBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0 , 48,40)];
        [cancalBtn setImage:img forState:UIControlStateNormal];
        [cancalBtn addTarget:self action:@selector(cancalBtnCkick) forControlEvents:UIControlEventTouchUpInside];
        [toolView addSubview:cancalBtn];
        
        UIButton *certainBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenW -60, 0, 45, 40)];
        [certainBtn setTitle:@"确定" forState:UIControlStateNormal];
        [certainBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
        certainBtn.titleLabel.font = kBaseFont_(14);
        [certainBtn addTarget:self action:@selector(certainBtnCkick) forControlEvents:UIControlEventTouchUpInside];
        [toolView addSubview:certainBtn];
        
        
        UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, kScreenW, 200)];
        pickerView.delegate = self;
        pickerView.dataSource = self;
        pickerView.backgroundColor = [UIColor whiteColor];
        self.pickerView = pickerView;
        [view addSubview:pickerView];
        
        
        _dateView = view;
        [self.view addSubview:view];
    }
    return _dateView;
}

- (void)cancalBtnCkick {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0);
        self.dateView.frame = CGRectMake(0, kScreenH, kScreenW, 240);
        
    } completion:^(BOOL finished) {
        [self.titleCoverView removeFromSuperview];
        [self.dateView removeFromSuperview];
    }];
    
    self.rightBarBtn.selected = NO;
}

- (void)certainBtnCkick {
    
    NSString *yearStr = [self pickerView:self.pickerView titleForRow:[self.pickerView selectedRowInComponent:0] forComponent:0];
    
    NSString *moonStr = [self pickerView:self.pickerView titleForRow:[self.pickerView selectedRowInComponent:1] forComponent:1];
    
    NSString *dateStr = [yearStr stringByAppendingString:moonStr];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy年MM月";
    NSDate *date = [fmt dateFromString:dateStr];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM";
    self.dateStr = [dateFormatter stringFromDate:date];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0);
        self.dateView.frame = CGRectMake(0, kScreenH, kScreenW, 240);
        
    } completion:^(BOOL finished) {
        [self.titleCoverView removeFromSuperview];
        [self.dateView removeFromSuperview];
    }];
    
    self.rightBarBtn.selected = NO;
    
    [self loadData];
}


#pragma mark -- piker
//
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return self.pickerArr.count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    return [self.pickerArr[component] count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.pickerArr[component][row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

@end
